<template>
  <div class="album">
    <div class="main">
      <div class="header">
        <el-form :inline="true">
          <el-form-item label="描述">
            <el-input placeholder="请输入图片描述" v-model="findAlbumQuery.description"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select placeholder="请选择状态" v-model="findAlbumQuery.status">
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="dateTime"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY/MM/DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="find">查询</el-button>
            <el-button @click="replace">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="photoHide = true">发布今天的第一张照片</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="deleteBatch">
              <el-icon><Minus /></el-icon>
              <span>批量删除</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="body" v-if="albumList.length > 0">
        <el-table :data="albumList" stripe @selection-change="handleSelectionChange">
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="图片">
            <template #default="scope">
              <el-image :src="scope.row.url" lazy loading="lazy"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="描述" prop="description"></el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              <span
                :class="scope.row.status === 0 ? 'blue' : 'red'"
                @click="updateStatus(scope.row.id, scope.row.status === 0 ? 1 : 0)"
                >{{ scope.row.status === 0 ? '启用' : '禁用' }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime"></el-table-column>
          <el-table-column label="修改时间" prop="updateTime"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" :text="true">编辑</el-button>
              <el-button type="danger" :text="true" @click="deleteById(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-empty v-else></el-empty>
      <div class="page">
        <el-pagination
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          v-model:current-page="findAlbumQuery.page"
          v-model:page-size="findAlbumQuery.pageSize"
          @current-change="handlePageChange"
          @size-change="hadnlePageSizeChange"
        ></el-pagination>
      </div>
      <el-dialog v-model="photoHide" width="500" title="每一个精彩的瞬间都值得被记录">
        <el-form :model="submitInfo" ref="addFormRef" :rules="rules">
          <el-form-item label="描述" prop="desc">
            <el-input
              placeholder="请输入照片描述"
              type="textarea"
              show-word-limit
              maxlength="50"
              v-model="submitInfo.desc"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-upload
              v-model:file-list="successImgArr"
              :action="serverUploadImg"
              :headers="{ token: token }"
              list-type="picture"
              :on-success="handleSuccess"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-error="handleError"
              :on-exceed="handleExceed"
              :limit="4"
            >
              <el-button>上传照片</el-button>
              <template #tip>
                <div class="el-upload__tip">每一个精彩的瞬间都值得被记录</div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addAlbum">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {
  addAlbumService,
  deleteBatchService,
  getAlbumListService,
  updateStatusService,
} from '@/api/Album'
import { serverStore } from '@/stores/server'
import { decryptData } from '@/utils/CryptoJSUtil'
import { Minus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, ref } from 'vue'

const { serverUploadImg } = serverStore()
const albumList = ref([{}])

const total = ref(null)
const dateTime = ref('')
const findAlbumQuery = ref({
  page: 1,
  pageSize: 5,
  description: '',
  status: null,
  startTime: '',
  endTime: '',
})

const find = () => {
  const obj = JSON.parse(JSON.stringify(dateTime.value))
  findAlbumQuery.value.startTime = obj[0]
  findAlbumQuery.value.endTime = obj[1]
  getAlbumList(findAlbumQuery.value)
}
const replace = () => {
  getAlbumList({
    page: 1,
    pageSize: 5,
    description: '',
    status: null,
    startTime: '',
    endTime: '',
  })
}

/**
 * 发布
 */
const submitInfo = ref({
  desc: '',
  photoList: [],
})
const addFormRef = ref()
// 表单校验
const rules = {
  desc: [
    {
      required: true,
      message: '照片描述不能为空',
      trigger: 'blur',
    },
  ],
}
const photoHide = ref(false)
// 上传图片的回调数据
const successImgArr = ref([])
// 上传成功的回调函数
const handleSuccess = () => {
  ElMessage.success('上传成功')
  if (successImgArr.value[0].response && typeof successImgArr.value[0].response === 'string') {
    try {
      const decrypted = decryptData(successImgArr.value[0].response)
      const url = JSON.parse(decrypted).msg
      console.log(url)
      submitInfo.value.photoList.push(url)
    } catch (err) {
      console.error('解密响应失败:', err)
    }
  }
}
const token = localStorage.getItem('token')
// 点击上传列表图片
const handlePreview = (file) => {
  console.log('列表', file)
}
// 移除出列表图片
const handleRemove = () => {
  ElMessage.success('移除图片')
  console.log('移除图片')
}
const handleError = () => {
  ElMessage.error('图片上传失败')
}
const handleExceed = () => {
  ElMessage.warning('超出上传图片上限')
}
// 新增相册
const addAlbum = () => {
  addFormRef.value.validate((valid) => {
    if (valid) {
      if (submitInfo.value.photoList.length === 0) {
        ElMessage.error('未上传任何照片')
        return false
      }
      // 通过表单校验
      addAlbumService(submitInfo.value).then(() => {
        photoHide.value = false
        getAlbumList(findAlbumQuery.value)
      })
    }
  })
}

/**
 * 修改照片状态
 * @param id
 * @param stauts
 */
const updateStatus = (id, stauts) => {
  updateStatusService(id, stauts).then(() => {
    getAlbumList(findAlbumQuery.value)
  })
}

const photoIds = ref([])
/**
 * 根据id删除照片数据
 * @param id
 */
const deleteById = (id) => {
  ElMessageBox.confirm('你确定删除这一张图片吗?', 'Warning', {
    type: 'warning',
    cancelButtonText: '取消',
    confirmButtonText: '确认',
  }).then(() => {
    photoIds.value.push(id)
    deleteBatchService(photoIds.value)
    photoIds.value = photoIds.value.filter((item) => item.id)
    getAlbumList(findAlbumQuery.value)
  })
}
/**
 * 复选框变化
 * @param row
 */
const handleSelectionChange = (row) => {
  const obj = JSON.parse(JSON.stringify(row))
  photoIds.value = []
  obj.forEach((item) => {
    photoIds.value.push(item.id)
  })
}
/**
 * 批量删除
 */
const deleteBatch = () => {
  if (photoIds.value.length === 0) {
    ElMessage.error('未选中任何数据')
    return false
  }
  ElMessageBox.confirm(`你确认删除这${photoIds.value.length}张照片吗?`, 'Warning', {
    cancelButtonText: '取消',
    confirmButtonText: '确认',
    type: 'warning',
  })
    .then(() => {
      deleteBatchService(photoIds.value).then(() => {
        getAlbumList(findAlbumQuery.value)
        photoIds.value = []
      })
    })
    .catch(() => {
      ElMessage.success('取消删除')
    })
}

/**
 * 分页相关
 */
const handlePageChange = (page) => {
  findAlbumQuery.value.page = page
  getAlbumList(findAlbumQuery.value)
}
const hadnlePageSizeChange = (pageSize) => {
  findAlbumQuery.value.pageSize = pageSize
  getAlbumList(findAlbumQuery.value)
}

/**
 * 获取照片数据
 * @param query
 */
const getAlbumList = async (query) => {
  const { data } = await getAlbumListService(query)
  total.value = data.total
  albumList.value = data.records
}

onMounted(() => {
  getAlbumList(findAlbumQuery.value)
})
</script>

<style lang="scss" scoped>
.album {
  padding: 15px;
  background-color: #f3f4f5;

  .main {
    min-height: 100vh;
    padding: 20px;
    background-color: #fff;
    border-radius: 7px;

    .header {
      :deep(.el-select__wrapper) {
        width: 150px;
      }
      :deep(.el-range-editor) {
        width: 230px;
      }
    }

    .page {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}

.blue {
  cursor: pointer;
  color: #37b4fd;
}
.red {
  cursor: pointer;
  color: red;
}
::v-deep.el-table .cell {
  text-align: center !important;
}
</style>